//
//  MainViewController.m
//  WordTutor
//
//  Created by lyh on 15/11/18.
//  Copyright © 2015年 lyh. All rights reserved.
//

#import "MainViewController.h"
#import "BodyScrollView.h"
#import "WordView.h"
#import "EVAHeadView.h"
#import "SettingViewController.h"
#import "FunctionViewController.h"


#import "CET4WordModel.h"

#import "StatementView.h"
#import "CET4DB.h"

#define angle2radian(x) ((x) / 180.0 * M_PI)
@interface MainViewController ()
/**
 *  背景图片的数组
 */
@property (nonatomic, strong) NSMutableArray *imageList;
/**
 *  背景计时器
 */
@property (nonatomic, strong) NSTimer *timer;
/**
 *  背景图片下标
 */
@property (nonatomic, assign) NSUInteger page;

@property (nonatomic, strong) BodyScrollView *bodyScrollView;

@property (nonatomic, strong) WordView *wordView;

//___________________________杨
@property (nonatomic, strong) NSMutableArray *cet4WordsArray;//数据库中表cet_four_word中的内容

@property (nonatomic, strong) NSMutableArray *cet4sentenceArray;//数据库中表cet_four_word中的内容

@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer;//向左轻扫手势

@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;//向右轻扫手势

@property (nonatomic, assign) NSInteger index;//数据数组的下标


@end

@implementation MainViewController

- (WordView *)wordView
{
    if (!_wordView) {
        self.wordView = [[WordView alloc] initWithFrame:CGRectMake(0, 64, 375, 375)];
    }
    return _wordView;
}

- (BodyScrollView *)scrollView
{
    if (!_bodyScrollView) {
        self.bodyScrollView = [[BodyScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    }
    return _bodyScrollView;
}

- (NSMutableArray *)imageList
{
    if (!_imageList) {
        self.imageList = [NSMutableArray arrayWithObjects:@"show_image_1.png", @"show_image_2.png", @"show_image_3.png", @"show_image_4.png", nil];
    }
    return _imageList;
}

- (void)createGradientBackground:(CGRect)rect with:(NSString*)bgurl{
    //Image background
    UIImage *bgImage=[UIImage imageNamed:bgurl];
    CGSize bgSize=bgImage.size;
    CGRect imageRect;
    if ((bgSize.width/bgSize.height)>(rect.size.width/rect.size.height)) {
        imageRect=CGRectMake(0, 0, rect.size.height*bgImage.size.width/bgImage.size.height, rect.size.height);
    }else{
        imageRect=CGRectMake(0, 0, rect.size.width,rect.size.width*bgImage.size.height/bgImage.size.width);
    }
    
    UIGraphicsBeginImageContext(imageRect.size);
    [bgImage drawInRect:imageRect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self addAction];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createGradientBackground:self.view.bounds with:[self.imageList objectAtIndex:0]];
    self.page = 1;
    
    //从数据库中查询的表cet_four_word中的内容
    self.cet4WordsArray = [CET4WordModel CET4WordModelArray];
    [self.view addSubview:self.wordView];
    
    self.cet4sentenceArray = [[CET4DB shareCET4DB] selectCet4sentence];
    [self.scrollView createViewsWithSuperView:self.view];
    [self.view addSubview:self.scrollView];
    
    //更新wordView和statementView的内容
    self.index = 1;
    [self updateViews:self.index];
    
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
//    
//    [self.wordView addGestureRecognizer:pan];
    
    //________________________杨
    //给self.wordView添加轻扫手势
    [self addSwipeGestureRecognizer];
}

/**————————————————杨
 *  更新Views上控件的内容
 *
 *  @param index 放置数据内容数组的下标
 */
-(void)updateViews:(NSInteger)index {
    //给WordsShowView中赋值
    [self.wordView updateWordView:self.cet4WordsArray[index]];
    //给examplesShowView中的控件赋值
    [self.bodyScrollView.statementView updateStatementView:self.cet4sentenceArray[index]];
}

-(void)addSwipeGestureRecognizer {
    //创建轻扫手势（并添加到wordsShowView上）
    //实例化向左轻扫手势
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognizerAction:)];
    //实例化向右轻扫手势
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognizerAction:)];
    
    //给向左轻扫手势添加轻扫方向
    self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    //给向右轻扫手势添加轻扫方向
    self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    //将轻扫手势添加到WordsShowView上
    [self.wordView addGestureRecognizer:self.leftSwipeGestureRecognizer];
    [self.wordView addGestureRecognizer:self.rightSwipeGestureRecognizer];
}


#pragma mark - 平移手势
- (void)pan:(UIPanGestureRecognizer *)pan
{
    //关键帧动画
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    
    anim.keyPath = @"transform.rotation.y";
    
    anim.values = @[@(angle2radian(-180)),@(angle2radian(180))];
    
    anim.repeatCount = 1;
    
    anim.duration = 1.f;
    
    // 给图层添加了动画
    [self.wordView.layer addAnimation:anim forKey:nil];
    
}

-(void)swipeGestureRecognizerAction:(UISwipeGestureRecognizer *)swipeGestureRecognizer {
    NSLog(@"轻扫了");
    
    if (swipeGestureRecognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        if (self.index < self.cet4WordsArray.count - 1) {
            self.index += 1;
        } else {
            self.index = 0;
        }
        [self updateViews:self.index];
    }
    if (swipeGestureRecognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        if (self.index >= 1) {
            
            self.index -= 1;
            
        } else {
            self.index = self.cet4WordsArray.count - 1;
        }
    }
    [self updateViews:self.index];
}


#pragma mark - 启动计时器
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.timer==nil) {
        self.timer=[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(switchImages) userInfo:nil repeats:YES];
    }
}
#pragma mark 计时器监听
- (void)switchImages
{
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    transition.delegate = self;
    [self.view.layer addAnimation:transition forKey:@"EaseInOut"];
    
    NSString *imageUrl = [_imageList objectAtIndex:self.page];
    [self createGradientBackground:self.view.bounds with:imageUrl];
    self.page=(self.page+1)%_imageList.count;
}
# pragma mark 销毁计时器
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (_timer!=nil) {
        [_timer invalidate];
        _timer=nil;
    }
}

-(void) addAction {
    [self.scrollView.headerView.rightBtn addTarget:self action:@selector(didClickBySetting:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.scrollView.headerView.leftBtn addTarget:self action:@selector(didClickByFun:) forControlEvents:UIControlEventTouchUpInside];
}

-(void) didClickBySetting: (UIButton *)sender {

    
    SettingViewController *vc = [[SettingViewController alloc]init];
    
    //动画++
    
    [self presentViewController:vc animated:NO completion:nil];
}

-(void) didClickByFun: (UIButton *)sender {
    FunctionViewController *vc = [FunctionViewController new];
    
    [self presentViewController:vc animated:YES completion:nil];
}


-(void)dealloc {
    NSLog(@"[200] ---%s ---%d", __func__, __LINE__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
